package com.jsyl.lwbk.business.service.education.impl;

import com.jsyl.lwbk.business.domain.education.TrainingProgram;
import com.jsyl.lwbk.business.dto.education.TrainingProgramDTO;
import com.jsyl.lwbk.business.dto.education.TrainingProgramListDTO;
import com.jsyl.lwbk.business.dto.education.UpdateTrainingProgramListDTO;
import com.jsyl.lwbk.business.domain.Question;
import com.jsyl.lwbk.business.mapper.QuestionMapper;
import com.jsyl.lwbk.business.mapper.education.TrainingProgramMapper;
import com.jsyl.lwbk.business.service.education.ITrainingProgramService;
import com.jsyl.lwbk.common.enums.InputTypeEnum;
import com.jsyl.lwbk.common.enums.ModifyDirectionEnum;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author jh
 * @date 2020-11-02 16:18
 * @desc
 **/
@Service
public class TrainingProgramServiceImpl implements ITrainingProgramService {

    private static final Logger log = LoggerFactory.getLogger(TrainingProgramServiceImpl.class);

    @Autowired
    private TrainingProgramMapper trainingProgramMapper;
    @Autowired
    private QuestionMapper questionMapper;


    @Override
    public TrainingProgram findbyId(Long id) {
        return trainingProgramMapper.selectById(id);
    }

    @Override
    public List<TrainingProgram> findList(TrainingProgramListDTO trainingProgramListDTO) {
        return trainingProgramMapper.findList(trainingProgramListDTO);
    }

    @Override
    public List<TrainingProgram> findTrainingProgramList(String trainingProgramNumber) {
        return trainingProgramMapper.findTrainingProgramList(trainingProgramNumber);
    }

    @Override
    public List<TrainingProgram> listAvaliable(TrainingProgramListDTO trainingProgramListDTO) {
        return trainingProgramMapper.listAvaliable(trainingProgramListDTO);
    }

    @Override
    public void updateTrainingLevel(String sql) {
        trainingProgramMapper.updateTrainingLevel(sql);
    }

    @Override
    @Transactional
    public void update(UpdateTrainingProgramListDTO updateTrainingProgramListDTO, String loginName) {
        //根据题目模块+题目+题目分数 筛选出题目，全部设置为已删除。
        trainingProgramMapper.updateTrainingProgramDelete(updateTrainingProgramListDTO.getEvaluateModuleType(), updateTrainingProgramListDTO.getQuestionId(), updateTrainingProgramListDTO.getTrainingScore());
        List<TrainingProgramDTO> trainingProgramDTOS = updateTrainingProgramListDTO.getTrainingProgramDTO();
        if(!CollectionUtils.isEmpty(trainingProgramDTOS)) {
            //更新/维护/插入
            for (int i=0;i<trainingProgramDTOS.size();i++) {
                   TrainingProgramDTO trainingProgramDTO = trainingProgramDTOS.get(i);
                   checkTrainingProgramDTO(trainingProgramDTO,i);
                    //题目未存在，则更新插入
                    Integer projectType = null;
                    if (trainingProgramDTO.getId() == null) {
                        if(updateTrainingProgramListDTO.getQuestionId() != null){
                            Question question = questionMapper.selectById(updateTrainingProgramListDTO.getQuestionId());
                            if(question!=null){
                                projectType = question.getProjectType();
                            }
                        }
                    TrainingProgram trainingProgram = new TrainingProgram();
                    BeanUtils.copyProperties(trainingProgramDTO, trainingProgram);
                    trainingProgram.setProjectType(projectType);
                    trainingProgram.setProjectModule(updateTrainingProgramListDTO.getEvaluateModuleType());
                    trainingProgram.setTrainingScore(updateTrainingProgramListDTO.getTrainingScore());
                    trainingProgram.setQuestionId(updateTrainingProgramListDTO.getQuestionId());
                    trainingProgram.setCreateTime(new Date());
                    trainingProgram.setUpdateTime(new Date());
                    trainingProgram.setProgramDelete(0);
                    trainingProgram.setCreateBy(loginName);
                    trainingProgramMapper.insert(trainingProgram);
                } else {//题目存在，则更新操作
                    TrainingProgram trainingProgram = trainingProgramMapper.selectById(trainingProgramDTO.getId());
                    BeanUtils.copyProperties(trainingProgramDTO, trainingProgram);
                    trainingProgram.setProgramDelete(0);
                    trainingProgram.setUpdateTime(new Date());
                    trainingProgram.setUpdateBy(loginName);
                    trainingProgramMapper.updateById(trainingProgram);
                }
            }
        }
    }

    private void checkTrainingProgramDTO(TrainingProgramDTO trainingProgram,int i){
        if(StringUtils.isEmpty(trainingProgram.getTrainingName())){
            throw new BusinessException("第"+(i+1)+"行训练项目名称为空");
        }
        if(StringUtils.isEmpty(trainingProgram.getTrainingContent())){
            throw new BusinessException("第"+(i+1)+"行训练项目描述为空");
        }
        if(trainingProgram.getInputType() == null){
            throw new BusinessException("第"+(i+1)+"行输入类型为空");
        }
        if(trainingProgram.getModifyDirection() == null){
            throw new BusinessException("第"+(i+1)+"行修改方向为空");
        }
        String modifyContent = trainingProgram.getModifyContent();
        if(StringUtils.isEmpty(modifyContent)){
            throw new BusinessException("第"+(i+1)+"行修改内容为空");
        }
        if(!modifyContent.contains("[") || !modifyContent.contains("]")){
            throw new BusinessException("第"+(i+1)+"行修改内容格式不正确(正确格式: xx[66]xx)");
        }

        String value = modifyContent.substring(modifyContent.indexOf("[")+1,modifyContent.indexOf("]"));
        if(StringUtils.isEmpty(value) || !value.matches("^[1-9]\\d*|0$")){
            throw new BusinessException("第"+(i+1)+"行修改内容中的值需为正整数");
        }
    }




    @Override
    @Transactional
    public String importTrainingProgram(List<TrainingProgram> programList,String operName) {
        if (StringUtils.isNull(programList) || programList.size() == 0) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        trainingProgramMapper.updateTrainingProgramDelete(programList.get(0).getProjectModule(),null,null);
        for (int i=0;i<programList.size();i++) {
            TrainingProgram paramProgram = programList.get(i);
            checkTrainingProgram(paramProgram,i);
            try {
                Integer projectType = null;
                Question question = questionMapper.selectById(paramProgram.getQuestionId());
                if(question!=null){
                    projectType = question.getProjectType();
                }
                TrainingProgram trainingProgram = new TrainingProgram();
                BeanUtils.copyProperties(paramProgram, trainingProgram);
                trainingProgram.setProjectType(projectType);
                trainingProgram.setProjectModule(paramProgram.getProjectModule());
                trainingProgram.setTrainingScore(paramProgram.getTrainingScore());
                trainingProgram.setQuestionId(paramProgram.getQuestionId());
                trainingProgram.setInputType(InputTypeEnum.getInputtype(trainingProgram.getInputTypeStr()));
                trainingProgram.setModifyDirection(ModifyDirectionEnum.getModifyDirection(trainingProgram.getModifyDirectionStr()));
                trainingProgram.setCreateTime(new Date());
                trainingProgram.setUpdateTime(new Date());
                trainingProgram.setProgramDelete(0);
                trainingProgram.setCreateBy(operName);
                trainingProgramMapper.insert(trainingProgram);
                successNum++;
//                successMsg.append("<br/>" + successNum + "、项目名称 " + paramProgram.getTrainingName() + " 更新成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、项目名称 " + paramProgram.getTrainingName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new BusinessException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
        return "导入成功";
    }


    private void checkTrainingProgram(TrainingProgram trainingProgram,int i){
        if(trainingProgram.getProjectModule() == null){
            throw new BusinessException("第"+(i+2)+"测评类型为空");
        }
        if(trainingProgram.getQuestionId() == null){
            throw new BusinessException("第"+(i+2)+"题目ID为空");
        }
        if(trainingProgram.getTrainingScore() == null){
            throw new BusinessException("第"+(i+2)+"题目分值为空");
        }
        if(StringUtils.isEmpty(trainingProgram.getTrainingName())){
            throw new BusinessException("第"+(i+2)+"行训练项目名称为空");
        }
        if(StringUtils.isEmpty(trainingProgram.getTrainingContent())){
            throw new BusinessException("第"+(i+2)+"行训练项目描述为空");
        }
        if(StringUtils.isEmpty(trainingProgram.getInputTypeStr())){
            throw new BusinessException("第"+(i+2)+"行输入类型为空");
        }
        if(InputTypeEnum.getInputtype(trainingProgram.getInputTypeStr()) == null){
            throw new BusinessException("第"+(i+2)+"行输入类型不正确");
        }
        if(StringUtils.isEmpty(trainingProgram.getModifyDirectionStr())){
            throw new BusinessException("第"+(i+2)+"行修改方向为空");
        }
        if(ModifyDirectionEnum.getModifyDirection(trainingProgram.getModifyDirectionStr()) == null){
            throw new BusinessException("第"+(i+2)+"行修改方向不正确");
        }
        String modifyContent = trainingProgram.getModifyContent();
        if(StringUtils.isEmpty(modifyContent)){
            throw new BusinessException("第"+(i+2)+"行修改内容为空");
        }
        if(!modifyContent.contains("[") || !modifyContent.contains("]")){
            throw new BusinessException("第"+(i+2)+"行修改内容格式不正确(正确格式: xx[66]xx)");
        }

        String value = modifyContent.substring(modifyContent.indexOf("[")+1,modifyContent.indexOf("]"));
        if(StringUtils.isEmpty(value) || !value.matches("^[1-9]\\d*|0$")){
            throw new BusinessException("第"+(i+2)+"行修改内容中的值需为正整数");
        }
    }

    @Override
    public int subjectCount(Long questionId, Integer trainScore) {
        return trainingProgramMapper.subjectCount(questionId,trainScore);
    }
}
